package com.by_man.presenter.module_member_activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.main_page.MainActivity;
import com.by_man.presenter.module_gestureLock.GestureLockActivity;
import com.by_man.repository.IpAddress;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by man on 2017-02-27.
 */
public class NewsActivity extends AppCompatActivity {
    private String meetingname;
    private String maxStr;

    private Handler handler;
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                initView();
            }
        };
        if (0 == UserInfos.All_New_Activity_Detail.size()) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("提示信息");
            progressDialog.setMessage("正在请求数据，请稍后......");
            progressDialog.setCancelable(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();

            Thread thread = new Thread() {
                public void run() {
                    while (0 == UserInfos.All_New_Activity_Detail.size()) {        // 阻塞等待数据的初始化

                    }
                    progressDialog.dismiss();
                    Message message = Message.obtain(handler);
                    message.sendToTarget();
                }
            };
            thread.setDaemon(true);             // 设置为守护线程
            thread.start();
        } else {
            initView();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(this, MainActivity.class);
                intent.putExtra("position", 3);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("position", 3);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode,event);
    }

    protected void onRestart()
    {
        super.onRestart();
        Intent intent=new Intent(this,GestureLockActivity.class);
        intent.putExtra("class",this.getClass().getName());
        intent.putExtra("position", 3);
        startActivity(intent);
    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        // 取出会议详情,设置页面
        final Button attendBtn = (Button) findViewById(R.id.attend);


        JSONArray jsonArray = LocalDataManager.getNewActivityDetail(getIntent().getStringExtra("extra_data"));
        if (null != jsonArray) {
            try {
                JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                TextView newstitle = (TextView) findViewById(R.id.meetingtitle);
                TextView newssholder = (TextView) findViewById(R.id.original);
                TextView deadline = (TextView) findViewById(R.id.deadline);
                TextView newscontent = (TextView) findViewById(R.id.meetingcontent);
                newscontent.setMovementMethod(new ScrollingMovementMethod());
                TextView max = (TextView) findViewById(R.id.max);

                meetingname = jsonObject.getString("meeting_name");
                newstitle.setText(meetingname);
                newssholder.setText(jsonObject.getString("originator"));
                deadline.setText(jsonObject.getString("deadline"));
                newscontent.setText(jsonObject.getString("content"));
                maxStr = jsonObject.getString("num");
                max.setText(maxStr);

                if (jsonObject.getString("isAttend").equals("true")) {
                    attendBtn.setText("已报名");
                    attendBtn.setBackgroundColor(0xff6db88a);
                    attendBtn.setClickable(false);
                } else {
                    attendBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            showTips();
                        }
                    });
                }

            } catch (JSONException je) {

            }
        }
    }

    private void showTips() {
        AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("提醒")
                .setMessage("将为你报名该活动，您的顾问将为你安排相关事宜")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (null != meetingname) {  // 页面未初始化完成

                            final Button attendBtn = (Button) findViewById(R.id.attend);
                            JSONObject jsonObject = LocalDataManager.getActivityNumber(meetingname);
                            if (jsonObject != null) {
                                try {
                                    int isFull = jsonObject.getInt("num");
                                    TextView num = (TextView) findViewById(R.id.num);
                                    num.setText("" + isFull);
                                    int max = Integer.parseInt(maxStr);
                                    if (isFull >= max) {    // 不能报名
                                        attendBtn.setText("人数已满，停止报名");
                                        attendBtn.setBackgroundColor(0xff6db88a);
                                        attendBtn.setClickable(false);
                                    } else { // 可以报名。进行报名
                                        attendBtn.setText("已报名");
                                        attendBtn.setBackgroundColor(0xff6db88a);
                                        attendBtn.setClickable(false);
                                        // 进行报名
                                        RequestQueue rQueue = LocalDataManager.getRequestQueue();
                                        final HashMap<String, String> params = new HashMap<String, String>();
                                        params.put("token", UserInfos.token);
                                        params.put("arg", meetingname);
                                        JSONObject jsonObjectparams = new JSONObject(params);
                                        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
                                                IpAddress.Sign_Up, jsonObjectparams,
                                                new Response.Listener<JSONObject>() {
                                                    @Override
                                                    public void onResponse(JSONObject jsonObject) {
                                                        try {
                                                            if (jsonObject.getBoolean("isFull")) { // 不会执行
                                                                SharedApplication.showToast(NewsActivity.this, "报名成功");
                                                            }
                                                        } catch (JSONException je) {
                                                            je.printStackTrace();
                                                        }
                                                    }
                                                },
                                                new Response.ErrorListener() {
                                                    @Override
                                                    public void onErrorResponse(VolleyError volleyError) {
                                                        Log.e("NewsError",volleyError.getMessage(),volleyError);
                                                    }
                                                });
                                        rQueue.add(jsonObjectRequest);
                                    }
                                } catch (JSONException je) {
                                    je.printStackTrace();
                                }
                            }
                        } else {
                            SharedApplication.showToast(NewsActivity.this, "页面正在初始化，请稍后再试！");
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create();
        alertDialog.show();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
